import React, { useState, useEffect } from 'react';
import {
  Container,
  Typography,
  Box,
  Tabs,
  Tab,
  Paper,
  Alert,
} from '@mui/material';
import { userStorage } from '../../utils/api';
import ContentOperationLogs from './components/ContentOperationLogs';
import SystemLogs from './components/SystemLogs';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`logs-tabpanel-${index}`}
      aria-labelledby={`logs-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ py: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

const Logs: React.FC = () => {
  const [tabValue, setTabValue] = useState(0);
  const [user, setUser] = useState<any>(null);

  // 获取用户信息
  useEffect(() => {
    const userData = userStorage.get();
    setUser(userData);
  }, []);

  // 检查是否为管理员
  const isAdmin = user && (user.role === 'ADMIN' || user.role === 'SUPERADMIN');

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  if (!user) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
        <Alert severity="warning">
          请先登录以查看日志信息
        </Alert>
      </Container>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        系统日志
      </Typography>
      
      <Paper sx={{ mt: 3 }}>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={tabValue} onChange={handleTabChange} aria-label="日志类型选项卡">
            <Tab label="内容操作日志" id="logs-tab-0" aria-controls="logs-tabpanel-0" />
            {isAdmin && (
              <Tab label="系统日志" id="logs-tab-1" aria-controls="logs-tabpanel-1" />
            )}
          </Tabs>
        </Box>

        <TabPanel value={tabValue} index={0}>
          <ContentOperationLogs />
        </TabPanel>

        {isAdmin && (
          <TabPanel value={tabValue} index={1}>
            <SystemLogs />
          </TabPanel>
        )}
      </Paper>
    </Container>
  );
};

export default Logs; 